import { createRouter, createWebHashHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import FrontendLayout from "../layout/FrontendLayout.vue";
import BackendLayout from "../layout/BackendLayout.vue";
import { beforeEachHandler, afterEachHandler } from "./permession";

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      redirect: "/frontend/blog/list",
      component: HomeView,
    },
    {
      path: "/frontend",
      component: FrontendLayout,
      children: [
        {
          name: "FrontendBlogList",
          // 当 /frontend/blog/list 匹配成功
          // BlogList 将被渲染到 FrontendLayout 的 <router-view> 内部
          path: "blog/list",
          component: () => import("@/views/frontend/BlogList.vue"),
        },
        {
          name: "FrontendBlogDetail",
          path: "blog/detail",
          component: () => import("@/views/frontend/BlogDetail.vue"),
        },
      ],
    },
    {
      path: "/login",
      name: "LoginPage",
      component: () => import("@/views/login/LoginPage.vue"),
    },
    {
      path: "/backend",
      component: BackendLayout,
      children: [
        {
          name: "BackendBlogList",
          // 当 /backend/blog/list 匹配成功
          // BlogList 将被渲染到 BackendLayout 的 <router-view> 内部
          path: "blog/list",
          component: () => import("@/views/backend/BlogList.vue"),
        },
        {
          name: "BackendBlogCreate",
          // 当 /backend/blog/list 匹配成功
          // BlogList 将被渲染到 BackendLayout 的 <router-view> 内部
          path: "blog/create",
          component: () => import("@/views/backend/BlogCreate.vue"),
        },
        {
          name: "BackendTagList",
          // 当 /backend/tag/list 匹配成功
          // BlogList 将被渲染到 BackendLayout 的 <router-view> 内部
          path: "tag/list",
          component: () => import("@/views/backend/TagList.vue"),
        },
      ],
    },
    {
      path: "/404",
      name: "notFound",
      component: () => import("@/views/errors/NotFound.vue"),
    },
    {
      path: "/403",
      name: "permissionDeny",
      component: () => import("@/views/errors/PermissionDeny.vue"),
    },
    {
      path: "/:pathMatch(.*)*",
      redirect: "/404",
    },
  ],
});

// router的守卫导航
// 路由开始, 进入页面前的一些逻辑(权限检查)
router.beforeEach(beforeEachHandler);
// 路由完成
router.afterEach(afterEachHandler);

export default router;
